'use strict'

process.chdir(__dirname)

//引入模块
const titbit = require('titbit')
const fs = require('fs')
const dbcfg = require('./dbconfig.js')
const pg = require('pg')
const wxkey = require('./wxkey.js')
const { httpcli } = require('gohttp')
const token = require('titbit-token')
const tbloader = require('titbit-loader')
const { parsebody } = require('titbit-toolkit')

//校对文件目录
try {
  fs.accessSync('./images')
} catch (err) {
  fs.mkdirSync('./images')
}
try {
  fs.accessSync('./files')
} catch (err) {
  fs.mkdirSync('./files')
}
try {
  fs.accessSync('./files/music')
} catch (err) {
  fs.mkdirSync('./files/music')
}
try {
  fs.accessSync('./files/video')
} catch (err) {
  fs.mkdirSync('./files/video')
}
try {
  fs.accessSync('./files/voice')
} catch (err) {
  fs.mkdirSync('./files/voice')
}

//初始化postgresql
let psql = new pg.Pool(dbcfg)

//证书文件所在目录
let cert_path = '/usr/local/share'

//初始化app
const app = new titbit({
  //开启调试模式，若有错误会输出错误信息。
  maxBody: 20000000,
  debug: true,
  globalLog: true,
  server: {
   handshakeTimeout: 20000, //TLS握手连接（HANDSHAKE）超时
    //sessionTimeout: 350,
  },

  //设置服务器超时，毫秒单位，在具体的请求中，可以再设置请求的超时。
  timeout: 600000,
  //证书文件路径
  cert: `${cert_path}/wx.xxmtcds.top.pem`,
  key: `${cert_path}/wx.xxmtcds.top.key`
})

if (process.argv.indexOf('--local') > 0) {
  app.config.https = false;
  app.config.cert = app.config.key = '';
}

let tb = new tbloader();
tb.init(app);

//添加属性
app.addService('psql', psql);
app.addService('imagePath', `${__dirname}/images`);
app.addService('musicPath', `${__dirname}/files/music`);
app.addService('videoPath', `${__dirname}/files/video`);
app.addService('voicePath', `${__dirname}/files/voice`);

//管理员token
let tok = new token({
  //token有效期，单位为秒
  expires: 7200,
  //必须是32位字符
  key: '1qaz2wsx3edc4rfv5tgb6yhn7ujmki89',

  //必须是16位字符
  iv: '1q2w3e4r5t6y7u8i'
})
//用于管理员会话验证
app.addService('tok', tok)
// https://wx.xxmtcds.top:2333/music/2021-11-10_17-4-39_103380.mp3

//用户token
let usertok = new token({
  //token有效期，单位为秒
  expires: 7200,
  //必须是32位字符
  key: '1qaz2wsx3edc4rfv5tgb6yhn7ujm0967',

  //必须是16位字符
  iv: '112w3e4r5t667u78'
})
//用于用户端的会话验证
app.addService('usertok', usertok)

//小程序端调用wx.login进行登录验证，需要发送code到此请求。
app.get('/mp-login/:code', async c => {
  let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
    + `?appid=${wxkey.appid}`
    + `&secret=${wxkey.secret}`
    + `&js_code=${c.param.code}`
    + `&grant_type=authorization_code`

  let ret = await httpcli.get(auth_url)
    .then(res => {
      return res.json()
    });
  if (!ret.openid) {
    return c.status(500).send('获取授权信息失败。');
  }
  console.log(ret)
  let isFirst = await psql.query(`select * from elegant_user where user_id like '${ret.openid}'`)
  // console.log(isFirst.rows)
  if (!isFirst.rows[0]) {
    let inn = await psql.query(`insert into elegant_user(user_id) values('${ret.openid}')`)
    console.log(inn)
  }
  c.send({
    token: usertok.make(ret)
  });
});

app.use(new parsebody);

//运行在2333端口
app.run(2333);
